﻿using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Stock.Core.MongoDB;
using System.Linq;
using System.Threading.Tasks;
using Stock.Model;

namespace Stock.Core.Service
{
    public class stock_info_m: BaseMongoEntity
    {

        public stock_info data { get; set; }
        public long time { get; set; }
    }

    public interface IStockInfoService
    {
        Task<stock_info_m> insert(stock_info model);
        Task<BaseResult> getList(DateTime? starttime, DateTime? endtime = null);
        Task<BaseResult> getList(long starttime, long? endtime = null);
        Task<BaseResult> getLast();
    }

    public class StockService:IStockInfoService
    {
        MongoBaseRepository<stock_info_m> _mongo;

        public StockService(IMongoService mongo)
		{
            _mongo = mongo.Reposityory<stock_info_m>();
		}

        public async Task<stock_info_m>  insert(stock_info model)
		{
            model.id = Guid.NewGuid();
            stock_info_m s = new stock_info_m() { data = model, time = model.time };
			await _mongo.Create(s);
            var e = _mongo.GetQueryable().Where(a => a.data.id == s.data.id).SingleOrDefault();
            return e;
		}

        public async Task<BaseResult> getLast()
        {
			var qq = from l in _mongo.GetQueryable()
					 select l;

            var data = qq.OrderByDescending(q => q.time).First();
			return new BaseResult() { Data = data, DataCount = 1, IsSuccess = true };
        }

		

        public async Task<BaseResult> getList(DateTime? starttime, DateTime? endtime =null)
        {
			var qq = from l in _mongo.GetQueryable()
                                     select l;
			if (starttime != null)
                qq = qq.Where(aa => aa.data.date > starttime);
            if(endtime != null)
            {
                qq = qq.Where(aa => aa.data.date < endtime);
            }
            var data = qq.OrderByDescending(q => q.data.date).Take(10000).ToList();
			return new BaseResult() { Data = data, DataCount = qq.Count(), IsSuccess = true };
        }

        public async Task<BaseResult> getList(long starttime, long? endtime = null)
		{
			var qq = from l in _mongo.GetQueryable()
                                         where l.data.time > starttime
					 select l;
			if (endtime != null)
			{
                qq = qq.Where(aa => aa.data.time < endtime);
			}
            var data = qq.OrderByDescending(q => q.data.time).Take(10000).ToList();
			return new BaseResult() { Data = data, DataCount = qq.Count(), IsSuccess = true };
		}

       
    }
}
